<?php

declare(strict_types=1);

namespace App\Order\Controller;

use App\Common\Constants\ErrorCode;
use App\Common\Controller\AbstractController;
use App\Common\Middleware\JwtAuthMiddleware;
use App\Common\Middleware\PermissionMiddleware;
use App\Order\Request\OrderRefundRequest;
use App\Order\Service\OrderRefundService;
use App\Order\Service\OrderService;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\Middlewares;
use Hyperf\HttpServer\Annotation\RequestMapping;

/**
 * @Controller()
 * Class OrderRefundController
 * @package App\Order\Controller
 */
class OrderRefundController extends AbstractController
{
    /**
     * @Inject()
     * @var OrderRefundService
     */
    private $orderRefundService;

    /**
     * @Inject()
     * @var OrderService
     */
    private $orderService;

    /**
     * @RequestMapping(path="/v1/refund", methods="get")
     *
     * @Middlewares({
     *     @Middleware(JwtAuthMiddleware::class),
     *     @Middleware(PermissionMiddleware::class)
     * })
     * @param OrderRefundRequest $orderRefundRequest
     * @return array
     */
    public function index(OrderRefundRequest $orderRefundRequest)
    {
        $where = $orderRefundRequest->all();
        $field = [
            'shop.shop_name',
            'refund.refund_no',
            'refund.mid',
            'refund.shop_id',
            'refund.order_no',
            'refund.create_at',
            'refund.status',
            'refund.is_whole',
            'refund.refund_money',
            'refund.order_type',
            'refund.order_source',
            'member.phone',
            'member.phone as account',
            'refund.refund_at'
        ];
        $list = $this->orderRefundService->get($where, $field, (int)$where['perpage']);
        return $this->success($list->items(), '获取售后列表成功', $list->total());
    }

    /**
     * 退款订单详情基本信息
     *
     * @RequestMapping(path="/v1/refund/{refund_no}", methods="get")
     *
     * @Middlewares({
     *     @Middleware(JwtAuthMiddleware::class),
     *     @Middleware(PermissionMiddleware::class)
     * })
     * @param string $refund_no
     * @return array
     */
    public function refundBasic(string $refund_no)
    {
        $where = ['refund_no' => $refund_no];
        $refund = $this->orderRefundService->find($where, ['order_no']);

        $field = ['order_no', 'shop_id', 'mid', 'is_pay', 'status', 'create_at', 'deal_type', 'pay_type', 'order_phone',
            'address_id', 'order_type', 'pay_at', 'refund_at', 'complete_date', 'appointment_time','order_source'];
        $res = $this->orderService->find(['order_no' => $refund['order_no']], $field, $refund_no);
        if ($res['code'] == 0) {
            return $this->failed($res['errorCode'], $res['msg']);
        }
        return $this->success($res['data'], $res['msg']);
    }


    /**
     * 退款订单详情商品列表
     *
     * @RequestMapping(path="/v1/refund/{refund_no}/goods", methods="get")
     *
     * @Middlewares({
     *     @Middleware(JwtAuthMiddleware::class),
     *     @Middleware(PermissionMiddleware::class)
     * })
     * @param string $refund_no
     * @return array
     */
    public function refundGoods(string $refund_no)
    {
        $where = ['refund_no' => $refund_no];
        $field = ['refund_no', 'order_no', 'is_whole', 'status', 'refund_money', 'order_source', 'refund_commission'];
        $res = $this->orderRefundService->getRefundGoodsInfo($where, $field);
        $return = $this->success($res['goods'], '获取退款商品信息成功');
        $return['total_amount'] = $res['total_amount'];
        $return['total_commission'] = $res['total_commission'];
        return $return;
    }

    /**
     * 退款信息
     * @RequestMapping(path="/v1/refund/{refund_no}/reason", methods="get")
     *
     * @Middlewares({
     *     @Middleware(JwtAuthMiddleware::class),
     *     @Middleware(PermissionMiddleware::class)
     * })
     * @param string $refund_no
     * @return array
     */
    public function refundInfo(string $refund_no)
    {
        $where = ['refund_no' => $refund_no];
        $field = ['refund_memo', 'img_url'];
        $res = $this->orderRefundService->find($where, $field);
        if (empty($res['img_url'])) {
            $res['img_url'] = [];
        } else {
            $res['img_url'] = explode('|', $res['img_url']);
        }
        return $this->success($res, '获取退款信息成功');
    }


    /**
     * 售后退款操作
     * @RequestMapping(path="/v1/refund/{refund_no}", methods="put")
     *
     * @Middlewares({
     *     @Middleware(JwtAuthMiddleware::class),
     *     @Middleware(PermissionMiddleware::class)
     * })
     * @param string $refund_no
     * @return array|void
     */
    public function refundDo(string $refund_no)
    {
        $flag = $this->request->input('flag');
        $platform = $this->request->input('platform', 'web');
        if (empty($refund_no) || empty($platform) || (substr($refund_no, 0, 3) != 'XPT'))
            return $this->failed(ErrorCode::PARAMS_INVALID);
        if (!in_array($platform, ['web','mini','app']))
            return $this->failed(ErrorCode::PARAMS_INVALID, 'platform值无效');
        switch ($flag) {
            case 1:
                $res = $this->orderRefundService->refuse($refund_no, $platform);
                break;
            case 2:
                $res = $this->orderRefundService->agree($refund_no, $platform);
                break;
            default:
        }
        if ($res['code'] == 0) {
            return $this->failed($res['errorCode'], $res['msg']);
        }
        return $this->success([], $res['msg']);

    }


    /**
     * B端售后页面 退款提交
     * @RequestMapping(path="/v1/app/refund", methods="put")
     * @return array
     * @author liule
     * @date 2021-01-08 10:04
     */
    public function appRefundSubmit(){
        $order_no = $this->request->input('order_no', '');
        $refundParam = $this->request->input('goods_list', '');

        if (is_string($refundParam)) {
            $refundParam = json_decode($refundParam, true);
        }
        if (empty($refundParam) || empty($order_no)) {
            return $this->failed(ErrorCode::PARAMS_INVALID);
        }
        foreach ($refundParam as $k => $v){
            foreach (['goods_id','kz_self_num','refund_num'] as $vv){
                if (!array_key_exists($vv, $v))
                    return $this->failed(ErrorCode::PARAMS_INVALID, 'goods_list参数中键错误');
            }
        }
        $res = $this->orderRefundService->shopRefund($order_no, 1, $refundParam);

        if ($res['code'] == 0) {
            return $this->failed($res['errorCode'], $res['msg']);
        }
        return $this->success([], $res['msg']);
    }


    /**
     * 用户申请售后
     * @RequestMapping(path="/v1/api/refund/apply", methods="post")
     * @return array
     */
    public function applyRefundSubmit(){
        $param = $this->request->all();
        if (empty($param['order_no']) || empty($param['goods_list']) || !is_numeric($param['order_refund_status']) || !is_numeric($param['is_whole'])) {
            return $this->failed(ErrorCode::SYSTEM_INVALID);
        }
        $param['goods_list'] = json_decode($param['goods_list'], true);
        if (!is_array($param['goods_list'])) {
            return $this->failed(ErrorCode::SYSTEM_INVALID, '商品传参异常');
        }

        if(empty($param['refund_memo'])){
            return $this->failed(ErrorCode::SYSTEM_INVALID, '请您填写退款原因哦~,方便门店给您提供更好的服务');
        }

        $order = $this->orderService->findFirst(['order_no' => $param['order_no']]);
        if (!$order || $order->is_pay == 0){
            return $this->failed(ErrorCode::SYSTEM_INVALID, '订单信息异常,请联系相关门店进行售后哦~');
        }
        $res = $this->orderRefundService->applyRefund($order, $param);
        if ($res['code'] == 0) {
            return $this->failed($res['errorCode'], $res['msg']);
        }
        return $this->success($res['data'], $res['msg']);
    }

}
